<template>
  <div class="materialClassAdd" v-loading="detailInfoShow">
    <div v-if="!selectionpersonnelShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-if="pageType !== 'detail'"
          class="btn save"
          @click="handleAddSave(materialClassFormRef)"
          v-preventReClick
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >保存</el-button
        >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-collapse v-model="activeNames">
        <!-- 基础信息 -->
        <el-collapse-item name="1" class="transform-down">
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title"
              >{{
                pageType === "detail"
                  ? ""
                  : pageType === "add"
                  ? "新增"
                  : pageType == "share"
                  ? "分享"
                  : "编辑"
              }}文件夹</span
            >
          </template>
          <div class="materialClass-info">
            <el-form
              :model="materialClassForm"
              ref="materialClassFormRef"
              :rules="queryRules"
              label-width="100"
              v-enterToNext
              :disabled="pageType === 'detail'"
            >
              <el-row>
                <el-col :span="6" v-if="pageType != 'share'">
                  <el-form-item label="文件夹名称:" prop="folderName">
                    <el-input
                      ref="refInput"
                      v-model="materialClassForm.folderName"
                      placeholder="请输入"
                      clearable
                      maxlength="20"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="pageType != 'share'">
                  <el-form-item
                    label="文件类型:"
                    prop="folderType"
                    label-width="100"
                  >
                    <el-select
                      v-model="materialClassForm.folderType"
                      placeholder="请选择"
                      clearable
                      class="search-select"
                      @change="handleChildCategory"
                      disabled
                    >
                      <el-option
                        v-for="dict in filetypeList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                  v-if="
                    pageType == 'share' ||
                    (pageType != 'share' && materialClassForm.folderType == 0)
                  "
                >
                  <el-form-item
                    label="协作类型:"
                    prop="targetType"
                    label-width="100"
                  >
                    <el-select
                      v-model="materialClassForm.targetType"
                      placeholder="请选择"
                      clearable
                      class="search-select"
                      @change="handleChildCategory"
                      :disabled="pageType == 'edit'"
                    >
                      <el-option
                        v-for="dict in flagList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                  v-if="
                    (materialClassForm.targetType === 0 &&
                      materialClassForm.folderType === 0) ||
                    (pageType == 'share' && materialClassForm.targetType === 0)
                  "
                >
                  <el-form-item
                    label="选择部门:"
                    prop="selectdepartment"
                    label-width="100"
                  >
                    <!-- collapse-tags-tooltip -->
                    <el-tree-select
                    collapse-tags
                    show-checkbox
                      style="width: 100%"
                      ref="refSelect"
                      v-model="materialClassForm.selectdepartment"
                      :data="deptOptions"
                      :props="{
                        value: 'deptId',
                        label: 'deptName',
                        children: 'children',
                      }"
                      value-key="deptId"
                      placeholder="选择上级部门"
                      multiple
                      clearable
                      :check-strictly="true"
                      :render-after-expand="false"
                      @change="handlerselectdepartment"
                      :disabled="pageType != 'share' && !isAdmin"
                    />
                  </el-form-item>
                  <!-- :disabled="pageType !== 'share'" -->
                </el-col>
                <el-col
                  :span="6"
                  v-if="
                    (activeindex != 2 || pageType == 'share') &&
                    materialClassForm.targetType === 1
                  "
                >
                  <el-form-item
                    label="选择人员:"
                    prop="selectpronnel"
                    label-width="100"
                  >
                    <el-input
                      v-model="materialClassForm.selectpronnel"
                      v-show="false"
                    ></el-input>
                    <el-button @click="hangdlerselect" v-preventReClick
                      >选择人员</el-button
                    >
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                  v-if="
                    (materialClassForm.targetType === 2 &&
                      materialClassForm.folderType === 0) ||
                    (pageType == 'share' && materialClassForm.targetType === 2)
                  "
                >
                  <el-form-item
                    label="选择角色:"
                    prop="roles"
                    label-width="100"
                  >
                    <el-select
                      v-model="materialClassForm.roles"
                      placeholder="请选择"
                      clearable
                      class="search-select"
                      style="height: 100%"
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      :max-collapse-tags="3"
                      @change="handlerselectRole"
                    >
                      <el-option
                        v-for="item in roleOptions"
                        :key="item.roleId"
                        :label="item.roleName"
                        :value="item.roleId"
                        :disabled="item.status == 1"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <!-- 已选择的人员或部门 -->
        <template v-if="materialClassForm.targetType !== underfined">
          <el-collapse-item
            name="1"
            class="transform-down"
            v-if="
              ((activeindex != 2 || pageType == 'share') &&
                ((pageType != 'share' && materialClassForm.targetType != 0) ||
                  isAdmin)) ||
              pageType == 'share'
            "
          >
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title"
                >已选择的{{
                  materialClassForm.targetType == 0 ? "部门" :materialClassForm.targetType == 1? "人员":'角色'
                }}</span
              >
            </template>
            <div
              class="select-info"
              v-if="
                (activeindex != 2 || pageType == 'share') &&
                materialClassForm.targetType == 1
              "
            >
              <div class="select-table">
                <div class="table-top">
                  <div class="top-item">操作</div>
                  <div class="top-item">权限类型</div>
                  <div class="top-item">序号</div>
                  <div class="top-item">头像</div>
                  <div class="top-item">人员</div>
                  <div class="top-item">部门</div>
                </div>
                <div
                  class="table-bottom"
                  v-for="(item, index) in selectlist"
                  :key="index"
                >
                  <div class="top-item">
                    <el-icon
                      title="删除"
                      color="#E33838"
                      style="transform: translateY(5px)"
                      :style="index != 0 ? 'cursor:pointer;' : 'cursor:no-drop'"
                      :size="20"
                      @click="index != 0 ? deleteSelectlist(item, index) : ''"
                    >
                      <Delete />
                    </el-icon>
                  </div>
                  <div class="top-item">
                    <div class="selectstyle">
                      <el-select
                        v-model="item.permissionType"
                        placeholder="请选择"
                        :disabled="pageType != 'share' ? index == 0 : true"
                      >
                        <el-option
                          v-for="dict in authorityList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </div>
                  </div>
                  <div class="top-item">{{ index + 1 }}</div>
                  <div class="top-item">
                    <el-image
                      :preview-teleported="true"
                      style="
                        width: 30px;
                        height: 30px;
                        transform: translateY(8px);
                      "
                      :src="item.avatar"
                      :preview-src-list="[item.avatar]"
                    >
                    </el-image>
                  </div>
                  <div class="top-item">{{ item.nickName }}</div>
                  <div class="top-item">
                    {{
                      item.dept
                        ? item.dept.deptName
                          ? item.dept.deptName
                          : "--"
                        : "--"
                    }}
                  </div>
                </div>
                <div class="table-all">
                  <div class="top-item">全选修改:</div>
                  <div class="top-item">
                    <div class="selectstyle">
                      <el-select
                        v-model="selectpersonnel"
                        placeholder="请选择"
                        @change="handlerselectpersonnel"
                        :disabled="pageType != 'share' ? false : true"
                      >
                        <el-option
                          v-for="dict in authorityList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="select-info" v-if="materialClassForm.targetType == 0">
              <div class="select-table">
                <div class="table-top">
                  <div class="top-item">操作</div>
                  <div class="top-item">权限类型</div>
                  <div class="top-item">序号</div>
                  <div class="top-item">部门</div>
                </div>
                <div
                  class="table-bottom"
                  v-for="(item, index) in selectlist"
                  :key="index"
                >
                  <div class="top-item">
                    <el-icon
                      title="删除"
                      color="#E33838"
                      style="transform: translateY(5px)"
                      :size="20"
                      @click="deleteSelectlist(item, index)"
                    >
                      <Delete />
                    </el-icon>
                  </div>
                  <div class="top-item">
                    <div class="selectstyle">
                      <el-select
                        v-model="item.permissionType"
                        placeholder="请选择"
                        :disabled="pageType != 'share' ? false : true"
                      >
                        <el-option
                          v-for="dict in authorityList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </div>
                  </div>
                  <div class="top-item">{{ index + 1 }}</div>
                  <div class="top-item1">
                    {{ item.deptName ? item.deptName : "--" }}
                  </div>
                </div>
                <div class="table-all">
                  <div class="top-item">全选修改:</div>
                  <div class="top-item">
                    <div class="selectstyle">
                      <el-select
                        v-model="selectdept"
                        placeholder="请选择"
                        @change="handlerselectdept"
                        :disabled="pageType != 'share' ? false : true"
                      >
                        <el-option
                          v-for="dict in authorityList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="select-info" v-if="materialClassForm.targetType == 2">
              <div class="select-table">
                <div class="table-top">
                  <div class="top-item">操作</div>
                  <div class="top-item">权限类型</div>
                  <div class="top-item">序号</div>
                  <div class="top-item">角色</div>
                </div>
                <div
                  class="table-bottom"
                  v-for="(item, index) in selectlist"
                  :key="index"
                >
                  <div class="top-item">
                    <el-icon
                      title="删除"
                      color="#E33838"
                      style="transform: translateY(5px)"
                      :size="20"
                      @click="deleteSelectlist(item, index)"
                    >
                      <Delete />
                    </el-icon>
                  </div>
                  <div class="top-item">
                    <div class="selectstyle">
                      <el-select
                        v-model="item.permissionType"
                        placeholder="请选择"
                        :disabled="pageType != 'share' ? false : true"
                      >
                        <el-option
                          v-for="dict in authorityList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </div>
                  </div>
                  <div class="top-item">{{ index + 1 }}</div>
                  <div class="top-item1">
                    {{ item.roleName ? item.roleName : "--" }}
                  </div>
                </div>
                <div class="table-all">
                  <div class="top-item">全选修改:</div>
                  <div class="top-item">
                    <div class="selectstyle">
                      <el-select
                        v-model="selectdept"
                        placeholder="请选择"
                        @change="handlerselectdept"
                        :disabled="pageType != 'share' ? false : true"
                      >
                        <el-option
                          v-for="dict in authorityList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </template>
      </el-collapse>
    </div>
    <selectionpersonnel
      ref="selectionpersonnelRef"
      v-if="selectionpersonnelShow"
      v-model:selectionpersonnelShow="selectionpersonnelShow"
      :selectlist="selectlist"
      @submitChoose="handleSelectMaterial"
    />
  </div>
</template>

<script setup>
import { getDictsApi } from "@/api/dict";
import { getRolesList } from "@/api/system/user";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addMaterialClass,
  editMaterialClass,
} from "@/api/information/materialClass";
import selectionpersonnel from "./selectionpersonnel.vue";
import {
  getaddFolderApi,
  getauthorityApi,
  geteditdocApi,
  getshareApi,
  getDepartId,
  getRoleId,
} from "@/api/information/documentation.js";
import { listDeptAll } from "@/api/system/dept";
const { proxy } = getCurrentInstance();
import useUserStore from "@/store/modules/user";
//当前用户信息
const userStore = useUserStore();
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
  "clear",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  materialClassList: {
    type: Array,
    default: [],
  },
  Breadcrumbs: {
    type: Array,
    default: [],
  },
  activeindex: {
    type: Number,
    default: "",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 物料分类表单引用
const materialClassFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
//选择人员弹窗
const selectionpersonnelShow = ref(false);
// 输入框引用
const refInput = ref();
// 部门信息
const departInfo = ref();
// 是否为超级管理员角色
let isAdmin = ref(false);
const roleOptions = ref([]);
const roles = ref([]);
const roleSelf = ref([]);
const oldSelectdepartment = ref([]);
// 物料分类表单数据模板
const materialClassFormTemplate = {
  permissions: [],
  selectdepartment: [],
};
const selectlist =
  props.pageType == "share"
    ? ref([])
    : ref([
        {
          userId: userStore.id,
          avatar: userStore.avatar,
          nickName: userStore.nickName,
          permissionType: 0,
          dept: {
            deptName: userStore.deptName,
          },
        },
      ]);
const deptOptions = ref([]);

//是否有下级分类自定义校验
const isSubordinate = (rule, value, callback) => {
  if (
    value == 0 &&
    rowitem &&
    rowitem.children &&
    rowitem.children.length != 0
  ) {
    callback(new Error("该分类有下级分类，请删除下级分类后再修改此选项"));
  } else {
    callback();
  }
};
//防重复校验
const categoryNamevalidator = (rule, value, callback) => {
  let flag = props.materialClassList.find((element) => {
    return element.folderName == value;
  });
  if (flag) {
    callback(new Error("不能重复添加重复的名字"));
  } else {
    callback();
  }
};
const data = reactive({
  // 物料分类表单
  materialClassForm: JSON.parse(JSON.stringify(materialClassFormTemplate)),
  // 物料分类表单校验规则
  queryRules: {
    folderName: [
      { required: true, message: "请输入文件夹名称", trigger: "blur" },
      // { validator: categoryNamevalidator, trigger: "change" },
    ],
    targetType: [
      { required: true, message: "请选择协作类型", trigger: "change" },
      // { validator: isSubordinate, trigger: "change" },
    ],
    folderType: [
      { required: true, message: "请选择文件类型", trigger: "change" },
      // { validator: isSubordinate, trigger: "change" },
    ],
    selectpronnel: [
      { required: true, message: "请选择人员", trigger: "change" },
    ],
    selectdepartment: [
      { required: true, message: "请选择部门", trigger: "change" },
    ],
    roles: [{ required: true, message: "请选择角色", trigger: "change" }],
  },
  // 是否选项列表
  flagList: [
    {
      label: "按人员选",
      value: 1,
    },
    {
      label: "按部门选",
      value: 0,
    },
    {
      label: "按角色选",
      value: 2,
    },
  ],
});
const { materialClassForm, queryRules, flagList } = toRefs(data);

watch(
  // 监听的数据源
  () => selectlist.value.length,
  // 回调函数，在数据变化时执行
  (newValue, oldValue) => {
    if (newValue > 0) {
      materialClassForm.value.selectpronnel = "有值";
    } else {
      materialClassForm.value.selectpronnel = "";
    }
  },
  { immediate: true }
);
/** 查询菜单下拉树结构 */
let deptList = ref([]);
function getTreeselect() {
  deptOptions.value = [];
  listDeptAll().then((response) => {
    deptList.value = response.data;
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
}
/**
 * @description: 保存
 * @param {Object} materialClassFormRef 物料分类表单引用
 */
const handleAddSave = async (materialClassFormRef) => {
  if (!materialClassFormRef) return;
  await materialClassFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          if (props.pageType != "share") {
            selectlist.value.forEach((item) => {
              let id;
              if (props.pageType == "edit") {
                id = item.targetId;
              } else {
                id =
                  materialClassForm.value.targetType == 1
                    ? item.userId
                    : materialClassForm.value.targetType == 0
                    ? item.deptId
                    : item.roleId;
              }
              materialClassForm.value.permissions.push({
                targetType: materialClassForm.value.targetType,
                targetId: id,
                permissionType: item.permissionType,
              });
            });
          }
          let res;
          // if (
          //   materialClassForm.value.targetType === 0 &&
          //   materialClassForm.value.folderType === 0
          // ) {
          //   materialClassForm.value.permissions = [
          //     {
          //       targetType: materialClassForm.value.targetType,
          //       targetId: departInfo.value.deptId,
          //       permissionType: 0,
          //     },
          //   ];
          // }
          if (props.pageType == "edit") {
            res = await geteditdocApi(folderId.value, materialClassForm.value);
          } else if (props.pageType == "add") {
            if (props.Breadcrumbs[props.Breadcrumbs.length - 1].folderId != 0) {
              materialClassForm.value.parentFolderId =
                props.Breadcrumbs[props.Breadcrumbs.length - 1].folderId;
            }
            res = await getaddFolderApi(materialClassForm.value);
          } else if (props.pageType == "share") {
            let folderShareVos = [];
            multipleSelections.value.forEach((item) => {
              let obj = {
                folderId: item.children ? item.folderId : item.fileId,
                shareType: item.children ? 1 : 0,
                targetId: [],
                targetType: materialClassForm.value.targetType,
              };
              selectlist.value.forEach((jtem) => {
                obj.targetId.push(jtem.targetId);
              });
              folderShareVos.push(obj);
            });
            res = await getshareApi({ folderShareVos });
          }
          if (res.code === 200) {
            emit("update:materialClassAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            materialClassForm.value = JSON.parse(
              JSON.stringify(materialClassFormTemplate)
            );
            multipleSelections.value = [];
            selectlist.value = [];
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 删除
 */
const deleteSelectlist = (item, index) => {
  ElMessageBox.confirm("此操作将删除该选项，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          if (materialClassForm.value.targetType == 0) {
    materialClassForm.value.selectdepartment =
      materialClassForm.value.selectdepartment.filter((jtem) => {
        if (props.pageType == "edit") {
          return item.targetId != jtem;
        } else {
          return item.deptId != jtem;
        }
      });
  }
  selectlist.value.splice(index, 1);
        })
        .catch(() => {});

};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:materialClassAddShow", false);
    materialClassForm.value = JSON.parse(
      JSON.stringify(materialClassFormTemplate)
    );
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:materialClassAddShow", false);
        emit("clear");
        materialClassForm.value = JSON.parse(
          JSON.stringify(materialClassFormTemplate)
        );
      })
      .catch(() => {});
  }
};

const hangdlerselect = () => {
  selectionpersonnelShow.value = true;
};
/**
 * @description: 处理人员全选
 */
let selectpersonnel = ref(null);
const handlerselectpersonnel = (event) => {
  selectlist.value.forEach((item, index) => {
    if (index == 0) {
      item.permissionType = 0;
    } else {
      item.permissionType = event;
    }
  });
};
/**
 * @description: 处理部门全选
 */
let selectdept = ref(null);
const handlerselectdept = (event) => {
  selectlist.value.forEach((item) => {
    item.permissionType = event;
  });
};
/**
 * @description: 处理部门选择
 */
const handlerselectdepartment = () => {
  const isAdding = materialClassForm.value.selectdepartment.length > oldSelectdepartment.value.length;

  let event = materialClassForm.value.selectdepartment.slice(); // 复制当前选择的部门数组

  // 获取新增或删除的额外部门
  let extraItems = isAdding
    ? materialClassForm.value.selectdepartment.filter(item => !oldSelectdepartment.value.includes(item))
    : oldSelectdepartment.value.filter(item => !materialClassForm.value.selectdepartment.includes(item));

  // 处理新增或删除的额外部门及其所有子级
  const processDepartment = (deptId, isAdding) => {
    deptList.value.forEach(chilItem => {
      if (chilItem.parentId === deptId) {
        if (isAdding) {
          materialClassForm.value.selectdepartment.push(chilItem.deptId);
        } else {
          materialClassForm.value.selectdepartment = materialClassForm.value.selectdepartment.filter(Citem => Citem !== chilItem.deptId);
        }
        // 递归处理子部门
        if (chilItem.children) {
          processDepartment(chilItem.deptId, isAdding);
        }
      }
    });
  };

  // 处理额外部门及其所有子级的添加或删除
  extraItems.forEach(item => {
    deptList.value.forEach(chilItem => {
      if(item == chilItem.deptId) {
        if(chilItem.children) {
          chilItem.children.forEach(aItem => {
            materialClassForm.value.selectdepartment.forEach(bItem => {
                if(aItem.deptId == bItem) {
                  materialClassForm.value.selectdepartment = materialClassForm.value.selectdepartment.filter(Citem => Citem !== aItem.deptId);
                }
            })
          })
        }
      }
    })
    processDepartment(item, isAdding);
  });

  // 更新选择的部门列表
  selectlist.value = deptList.value.filter(item => materialClassForm.value.selectdepartment.includes(item.deptId));
  selectlist.value.forEach(item => {
    if (!item.permissionType && item.permissionType !== 0) {
      item.permissionType = 2;
    }
    item.targetId = item.deptId;
  });

  // 更新旧的选择部门数组
  oldSelectdepartment.value = materialClassForm.value.selectdepartment.slice();
};






function processChildren(children, toAdd, toRemove) {
  children.forEach(child => {
    if (!toAdd.includes(child.deptId)) {
      toRemove.push(child.deptId);
    }
    if (child.children) {
      processChildren(child.children, toAdd, toRemove);
    }
  });
}

/**
 * @description: 处理部门选择
 */
const handlerselectRole = (event,flag = false) => {
  selectlist.value = [];
  let arr = roleOptions.value.filter((item, index) => {
    return event.includes(item.roleId);
  });
  console.log(arr);
  selectlist.value.push(...arr);
  selectlist.value.forEach((item, index) => {
    if(!item.permissionType && item.permissionType !== 0) {
      item.permissionType = flag?0:2;
    }
    item.targetId = item.roleId;
  });
};

/**
 * @description: 处理人员选择
 */
const handleSelectMaterial = (value) => {
  if (value) {
    selectionpersonnelShow.value = false;
    if (value.length == 0) {
      selectlist.value = [
        {
          userId: userStore.id,
          avatar: userStore.avatar,
          nickName: userStore.nickName,
          permissionType: 0,
          dept: {
            deptName: userStore.deptName,
          },
        },
      ];
    } else {
      selectlist.value = [
        {
          userId: userStore.id,
          avatar: userStore.avatar,
          nickName: userStore.nickName,
          permissionType: 0,
          dept: {
            deptName: userStore.deptName,
          },
        },
        ...value
      ];
      // selectlist.value.shift()
      // selectlist.value.push(...value);
      // selectlist.value = value
      selectlist.value.forEach((item, index) => {
        if (props.pageType == "share") {
          item.permissionType = 3;
        } else {
          if (index == 0) {
            item.permissionType = 0;
          } else {
            item.permissionType = 2;
          }
        }
        if (item.userId) {
          item.targetId = item.userId;
        }
      });
      materialClassForm.value.selectpronnel = "有值";
    }
  } 
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
let folderId = ref(null);
const handleDetailInfo = async (row) => {
  try {
    detailInfoShow.value = true;
    folderId.value = row.folderId;
    getauthorityApi(row.folderId).then((res) => {
      selectlist.value = res.data;
      materialClassForm.value.selectpronnel = "有值";
      console.log("selectlist.value");
      console.log(res);
      console.log(selectlist.value);
      console.log(row);
      if (row.targetType == 0) {
        selectlist.value.forEach((item) => {
          item.dept = {
            deptName: item.deptName,
          };
          materialClassForm.value.selectdepartment.push(item.targetId);
        });
      } else if (row.targetType == 1) {
        selectlist.value.forEach((item) => {
          item.dept = {
            deptName: item.deptName,
          };
        });
      } else {
        selectlist.value.forEach((item) => {
          item.dept = {
            deptName: item.deptName,
          };
          materialClassForm.value.roles.push(item.targetId);
        });
      }
    });
    setTimeout(() => {
      materialClassFormRef.value.validateField("selectdepartment");
      materialClassFormRef.value.validateField("roles");
    }, 500);

    materialClassForm.value = row;
    materialClassForm.value.permissions = [];
    materialClassForm.value.selectdepartment = [];
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};
/**
 * @description: 处理分享信息
 * @param {Number} id
 */
let multipleSelections = ref([]);
const handleShareInfo = (multipleSelection) => {
  multipleSelections.value = multipleSelection;
};
/**
 * @description: 处理父组件id
 * @param {Number} id
 */
const handleParentId = (row) => {
  materialClassForm.value.parentFolderId = row.folderId;
};

/**
 * @description: 处理是否有下级分类改变
 */
const handleChildCategory = () => {
  if (materialClassForm.value.targetType == 0) {
    selectlist.value = [];
    if (props.pageType == "share") {
      selectlist.value = [];
      //       materialClassForm.value.selectdepartment = [departInfo.value.deptId];
      //         materialClassForm.value.permissions =[
      //     {
      //         "targetType": 0,
      //         "targetId": departInfo.value.deptId,
      //         "permissionType": 0
      //     }
      // ]
    } else {
      console.log(isAdmin.value);
      if (isAdmin.value) {
        materialClassForm.value.selectdepartment = [];
      } else {
        materialClassForm.value.selectdepartment = [departInfo.value.deptId];
        materialClassForm.value.permissions = [
          {
            targetType: 0,
            targetId: departInfo.value.deptId,
            permissionType: 0,
          },
        ];
      }
    }
  } else if (materialClassForm.value.targetType == 1) {
    if (props.pageType == "share") {
      selectlist.value = [];
    } else {
      selectlist.value = [
        {
          userId: userStore.id,
          avatar: userStore.avatar,
          nickName: userStore.nickName,
          permissionType: 0,
          dept: {
            deptName: userStore.deptName,
          },
        },
      ];
    }
  } else {
    // materialClassForm.value.roles = [];
    materialClassForm.value.roles = roleSelf.value;
    setTimeout(() => {
      handlerselectRole([...roleSelf.value],true);
    }, 500);
    if (props.pageType == "share") {
      selectlist.value = [];
    } else {
      selectlist.value = [];
    }
  }
};
/**
 * @description: 获取字典
 */
let authorityList = ref([]);
let filetypeList = ref([]);
let sharetypeList = ref([]);
async function getDicts() {
  getRolesList().then((response) => {
    roleOptions.value = response;
  });
  // 权限类型
  await getDictsApi("file_permission").then((res) => {
    if (res.code === 200) {
      authorityList.value = res.data;
    }
  });
  // 文件类型
  await getDictsApi("erp_folderType").then((res) => {
    if (res.code === 200) {
      filetypeList.value = res.data;
    }
  });
  // 获取当前登陆人二级部门
  await getDepartId().then((res) => {
    departInfo.value = res.data;
    // if (res.code === 200) {
    //   filetypeList.value = res.data;
    // }
  });
  await getRoleId().then((res) => {
    roleSelf.value = res.data;
  });
}

onMounted(() => {
  userStore.roles.forEach((item) => {
    if (item == "admin") {
      isAdmin.value = true;
    }
  });
  console.log("admin");
  console.log(userStore.roles);
  console.log(isAdmin.value);
  getDicts();
  getTreeselect();
  nextTick(() => {
    refInput.value.focus();
  });
  materialClassForm.value.folderType = props.activeindex - 1;
});

defineExpose({
  handleDetailInfo,
  handleParentId,
  handleShareInfo,
});
</script>
<style lang="scss" scoped>
.materialClassAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .materialClass-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  .select-info {
    .select-table {
      margin-top: 10px;
      .table-top {
        display: flex;
        background-color: #f8f8f8;
        height: 40px;
        font-size: 14px;
        .top-item {
          text-align: center;
          line-height: 40px;
          flex-grow: 1;
          border: 1px solid #ebeef5;
          border-right: unset;
          .selectstyle {
            display: flex;
            width: 160px;
            :deep(.el-icon svg) {
              width: 0;
              height: 0;
              border: 5px solid transparent;
              border-top-color: #6f6f6f;
              transform: translateY(4px);
            }
            :deep(.el-input__wrapper) {
              background: transparent !important;
              border: none !important;
              box-shadow: none !important;
            }
            :deep(.el-input__wrapper.is-focus) {
              box-shadow: none !important;
            }
            :deep(.el-select .el-input__wrapper.is-focus) {
              box-shadow: none !important;
            }
            :deep(.el-select .el-input.is-focus .el-input__wrapper) {
              box-shadow: none !important;
            }
          }
        }
        .top-item:nth-child(1) {
          width: 100px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:nth-child(2) {
          width: 180px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:nth-child(3) {
          width: 80px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:last-child {
          border-right: 1px solid #ebeef5;
        }
      }
      .table-bottom {
        display: flex;
        font-size: 14px;
        .top-item1 {
          text-align: center;
          line-height: 40px;
          flex-grow: 1;
          border: 1px solid #ebeef5;
        }
        .top-item {
          text-align: center;
          line-height: 40px;
          border: 1px solid #ebeef5;
          width: 419px;
          border-right: unset;
          border-top: unset;
          .selectstyle {
            display: flex;
            width: 160px;
            :deep(.el-icon svg) {
              width: 0;
              height: 0;
              border: 5px solid transparent;
              border-top-color: #6f6f6f;
              transform: translateY(4px);
            }
            :deep(.el-input__wrapper) {
              background: transparent !important;
              border: none !important;
              box-shadow: none !important;
            }
            :deep(.el-input__wrapper.is-focus) {
              box-shadow: none !important;
            }
            :deep(.el-select .el-input__wrapper.is-focus) {
              box-shadow: none !important;
            }
            :deep(.el-select .el-input.is-focus .el-input__wrapper) {
              box-shadow: none !important;
            }
          }
        }
        .top-item:nth-child(1) {
          width: 100px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:nth-child(2) {
          width: 180px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:nth-child(3) {
          width: 80px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:last-child {
          border-right: 1px solid #ebeef5;
        }
      }
      .table-all {
        display: flex;
        background-color: #f8f8f8;
        height: 40px;
        font-size: 14px;
        border: 1px solid #ebeef5;
        .top-item {
          text-align: center;
          line-height: 40px;
          flex-grow: 1;
          border-right: 1px solid #ebeef5;
          .selectstyle {
            display: flex;
            width: 160px;
            :deep(.el-icon svg) {
              width: 0;
              height: 0;
              border: 5px solid transparent;
              border-top-color: #6f6f6f;
              transform: translateY(4px);
            }
            :deep(.el-input__wrapper) {
              background: transparent !important;
              border: none !important;
              box-shadow: none !important;
            }
            :deep(.el-input__wrapper.is-focus) {
              box-shadow: none !important;
            }
            :deep(.el-select .el-input__wrapper.is-focus) {
              box-shadow: none !important;
            }
            :deep(.el-select .el-input.is-focus .el-input__wrapper) {
              box-shadow: none !important;
            }
          }
        }
        .top-item:nth-child(1) {
          width: 100px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:nth-child(2) {
          width: 180px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:nth-child(3) {
          width: 80px;
          text-align: center;
          flex: 0 0 auto;
        }
        .top-item:last-child {
          border-right: 1px solid #ebeef5;
        }
      }
    }
  }
  /* :deep(.el-select .el-input__wrapper) {
    height: 34px;
  } */
}
</style>
